import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/base_entity.dart';
import 'package:oramemo/entity/relation_query_entity.dart';
import 'package:oramemo/widget/my_button.dart';

class RelationSelectController extends GetxController {
  final TextEditingController customRelationController =
  TextEditingController();
  List<RelationQueryData> list = [];
  RelationQueryData? selectedRelation;

  @override
  void onInit() async {
    await onLoad(false);
    super.onInit();
  }

  Future<void> onLoad(bool isShowLoading) async {
    RelationQueryEntity? res = await DefaultApi()
        .oraDeviceRelationQueryGet<RelationQueryEntity>(
        isShowLoading: isShowLoading);
    list = res?.data ?? [];
    list.add(RelationQueryData()
      ..relationName = '自定义');
    update();
  }

  @override
  void onClose() {
    customRelationController.dispose();
    super.onClose();
  }

  void selectRelation(int relation) {
    if (relation == list.length - 1) {
      selectedRelation = null;
    } else {
      selectedRelation = list[relation];
    }
    update();
  }

  void saveRelation() async {
    if (selectedRelation?.id != null) {
      Get.back(result: selectedRelation);
    } else {
      String name = customRelationController.text;
      if (name.isNotEmpty) {
        BaseEntity? res = await DefaultApi()
            .oraDeviceRelationAddPost<BaseEntity>(
            relationName: name, isShowLoading: true);
        if (res?.isSuccess == true) {
          customRelationController.text = '';
          await onLoad(true);
          selectedRelation = list.last;
        }
      } else {
        Toast.show('请输入关系名');
      }
    }
  }

  void cancel() {
    Get.back();
  }
}

class RelationSelectPage extends StatelessWidget {
  final String? initialRelation;

  const RelationSelectPage({super.key, this.initialRelation});

  @override
  Widget build(BuildContext context) {
    final RelationSelectController controller =
    Get.put(RelationSelectController());

    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text(
          '与时光机使用者的关系',
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
        leading: TextButton(
          onPressed: controller.cancel,
          child: Text(
            '取消',
            style: TextStyle(
              color: Colors.black87,
              fontSize: 16.sp,
            ),
          ),
        ),
        actions: [
          Center(
            child: GetBuilder<RelationSelectController>(builder: (logic) {
              return Container(
                width: 79.w,
                height: 32.h,
                padding: EdgeInsets.only(right: 18.w),
                child: MyButton(
                  padding: EdgeInsets.zero,
                  onPressed: logic.saveRelation,
                  text: logic.selectedRelation?.id == null
                      ? '保存'
                      : '选择',
                  backgroundColor: Colours.app_main,
                  fontSize: 14.sp,
                  radius: 12.r,
                ),
              );
            }),
          )
        ],
      ),
      body: Column(
        children: [
          SizedBox(height: 11.h),
          Expanded(
            child: Container(
              color: Colors.white,
              child: GetBuilder<RelationSelectController>(builder: (logic) {
                return ListView.separated(
                  itemCount: controller.list.length,
                  separatorBuilder: (context, index) =>
                      Divider(
                        height: 1,
                        thickness: 0.5,
                        color: Colors.grey[300],
                        indent: 30.w,
                        endIndent: 30.w,
                      ),
                  itemBuilder: (context, index) {
                    final relation = controller.list[index];
                    return Column(
                      children: [
                        InkWell(
                          onTap: () => controller.selectRelation(index),
                          child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.symmetric(
                                horizontal: 30.w, vertical: 12.h),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  relation.relationName ?? '--',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    color: Colors.black,
                                  ),
                                ),
                                if (controller.selectedRelation?.id ==
                                    relation.id)
                                  Icon(
                                    Icons.check,
                                    color: Colors.blue,
                                    size: 24.sp,
                                  ),
                              ],
                            ),
                          ),
                        ),
                        if (index == controller.list.length - 1)
                          Column(
                            children: [
                              Container(
                                color: Colors.white,
                                padding: EdgeInsets.symmetric(horizontal: 30.w),
                                child: TextField(
                                  controller:
                                  controller.customRelationController,
                                  autofocus: false,
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    color: Colors.black,
                                  ),
                                  decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintText: '请输入与时光机关系',
                                    hintStyle: TextStyle(
                                      color: Colors.grey,
                                      fontSize: 16.sp,
                                    ),
                                  ),
                                  onChanged: (value) {},
                                ),
                              ),
                              Divider(
                                height: 1,
                                thickness: 0.5,
                                color: Colors.grey[300],
                                indent: 30.w,
                                endIndent: 30.w,
                              ),
                            ],
                          ),
                      ],
                    );
                  },
                );
              }),
            ),
          ),
        ],
      ),
    );
  }
}
